import { ref, computed } from "vue"
import { defineStore } from 'pinia'
import { wxLogin, getChatListAPI } from "@/api/index.js"
import { setStorage, getStorage, removeStorage } from "@/utils/common.js"

export const useUserStore = defineStore('user', () => {
	// 用户信息
	const userInfo = ref(getStorage("userInfo") || {})
	// 修改用户信息
	const setUserInfo = (info) => {
		Object.assign(userInfo.value, info)
		setStorage("userInfo", userInfo.value)
	}
	// 登录
	const login = async (code) => {
		const { data } = await wxLogin({ code })
		setStorage("userInfo", data)
		userInfo.value = data
		getChatList()
	}
	// 退出
	const logout = () => {
		userInfo.value = {}
		removeStorage('userInfo')
		uni.navigateTo({ url: '/pages/login-page/index' })
	}

	// 聊天列表
	const chatList = ref([])
	// 设置
	const setChatList = (item) => {
		chatList.value.unshift(item)
	}
	// 获取
	const getChatList = async () => {
		if (!userInfo.value.token) return
		const { data } = await getChatListAPI()
		chatList.value = data
	}
	// 会话id
	const sessionId = ref('')
	const setSessionId = (id) => {
		sessionId.value = id
	}


	return { userInfo, setUserInfo, login, logout, chatList, getChatList, setChatList, sessionId, setSessionId }
});